package com.ecp.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;

import com.ecp.base.service.AdminService;
import com.ecp.base.service.UserService;
import com.ecp.commons.Global;
import com.ecp.crm.bean.Admin;
import com.ecp.crm.bean.User;

public class WebUtil {
	public static final String SHOPPINGCART_SESSIONNAME = "shoppingCart_session"; // 购物车Session名称
	public static final String BROWSEHISTORY = "proBrowseHistory"; // 浏览记录Cookie名称
	public static final String FRONT_USER_COOKIENAME = "frontUser_cookie"; // 前台用户登录保存Cookie名称
	public static final String COOKIE_ENCODING = "UTF-8"; // Cookie保存中文时默认的编码方式
	public static final String TOKEN = "token";

	public static void out(HttpServletResponse response, String charset, String contentType,
			String data) {
		String content_type = contentType + ";charset=" + charset;
		response.setContentType(content_type);
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.println(data);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
	}

	public static Map<String, String> getRequestHeaders(HttpServletRequest request) {
		Map<String, String> maps = new HashMap<String, String>();
		@SuppressWarnings("unchecked")
		Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			String value = request.getHeader(name);
			maps.put(name, value);
		}
		return maps;
	}

	public static String getReferer(HttpServletRequest request) {
		return request.getHeader("Referer");
	}

	public static String HtmltoText(String inputString) {
		String htmlStr = inputString;
		String textStr = "";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		java.util.regex.Pattern p_ba;
		java.util.regex.Matcher m_ba;

		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
			String regEx_html = "<[^>]+>";
			String patternStr = "\\s+";

			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll("");

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll("");

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll("");

			p_ba = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
			m_ba = p_ba.matcher(htmlStr);
			htmlStr = m_ba.replaceAll("");

			textStr = htmlStr;

		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}
		return textStr;
	}

	public static String htmlZip(String content) {
		if (content == null) {
			return null;
		}
		String result = content.replaceAll("\r", "").replaceAll("\n", "")
				.replaceAll("<!--.*-->", "").replaceAll(">\\s*<", "><");
		return result;
	}

	public static String clearFckeditor(String content) {
		if (content == null) {
			return "";
		}
		content = content.replaceAll("\r\n", "");
		content = content.replaceAll("\"", "'");
		content = content.replaceAll("\r", "");
		content = content.replaceAll("\n", "");
		content = Pattern
				.compile("<script((?!</script).)*</script>",
						Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(content).replaceAll("");
		return content;
	}

	public static Integer getMerchantID(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session == null) {
			return 0;
		}
		if (session.getAttribute(Global.KEY_BACKEND_MERCHANT) == null) {
			return 0;
		}
		Integer merchantId = (Integer) session.getAttribute(Global.KEY_BACKEND_MERCHANT);
		return merchantId;
	}

	public static String getRemoteIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * @author zhanghao
	 *         ==========================================================
	 *         说明：解决Ajax跨域问题
	 * 
	 *         ==========================================================
	 */
	public static String getJSONCallBack(HttpServletRequest request, String result)
			throws Exception {
		return ServletRequestUtils.getStringParameter(request, "callback", "") + "(" + result
				+ ");";
	}

	/**
	 * 获取cookie的值
	 * 
	 * @param request
	 * @param name
	 *            cookie的名称
	 * @return
	 */
	public static String getCookieByName(HttpServletRequest request, String name) {
		Map<String, Cookie> cookieMap = WebUtil.readCookieMap(request);
		if (cookieMap.containsKey(name)) {
			Cookie cookie = (Cookie) cookieMap.get(name);
			String value = null;
			try {
				value = URLDecoder.decode(cookie.getValue(), WebUtil.COOKIE_ENCODING);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
			return value;
		} else {
			return null;
		}
	}

	protected static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (int i = 0; i < cookies.length; i++) {
				cookieMap.put(cookies[i].getName(), cookies[i]);
			}
		}
		return cookieMap;
	}

	public static void addMUserName(HttpSession session, String userName) {
		if (session != null) {
			session.setAttribute("MUserName", userName);
		}
	}

	public static void addOaAdmin(HttpServletRequest request, String oaAdmin) {
		HttpSession session = request.getSession();
		if (session != null) {
			session.setAttribute(Global.KEY_OA_ADMIN, oaAdmin);
		}
	}

	public static String getOaAdmin(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session == null) {
			return null;
		}
		String loginId = (String) session.getAttribute(Global.KEY_OA_ADMIN);
		return loginId;
	}

	/**
	 * 根据名称取得Session中的值
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static Object getSessionAttribute(HttpServletRequest request, String name) {
		HttpSession session = request.getSession();
		return (session != null ? session.getAttribute(name) : null);
	}

	public static boolean addCookie(HttpServletResponse response, String cookieName,
			String cookieVal, int time) {
		try {
			cookieVal = URLEncoder.encode(cookieVal, WebUtil.COOKIE_ENCODING);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return false;
		}
		Cookie cookie = new Cookie(cookieName, cookieVal);
		cookie.setPath("/");
		if (time > 0)
			cookie.setMaxAge(time);
		response.addCookie(cookie);
		return true;
	}

	public static void setResponseNoCache(HttpServletResponse response) {
		response.setHeader("progma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
	}

	public static void clearHtmlPageCache(HttpServletResponse response) {
		response.addHeader("Cache-Control", "no-store, must-revalidate");
		response.addHeader("Expires", "Thu, 01 Jan 1970 00:00:01 GMT");
	}

	public static void removeSessionAttribute(HttpServletRequest request, String name) {
		HttpSession session = request.getSession();
		if (session != null) {
			session.removeAttribute(name);
		}
	}

	public static String genToken(HttpServletRequest request) {
		String uuid = UUID.randomUUID().toString();
		String token = uuid.substring(0, 8) + uuid.substring(9, 13) + uuid.substring(14, 18)
				+ uuid.substring(19, 23) + uuid.substring(24);
		request.getSession().setAttribute(WebUtil.TOKEN, token);
		return token;
	}

	public static void clearToken(HttpServletRequest request) {
		request.getSession().removeAttribute(WebUtil.TOKEN);
	}

	public static String getHostName() {
		String name = "";
		try {
			InetAddress inetAddress = InetAddress.getLocalHost();
			name = inetAddress.getHostName();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return name;
	}

	/**
	 * 将登陆成功的会员添加到Session中
	 * 
	 * @param request
	 * @param user
	 */
	public static void addFrontUser(HttpSession session, User user) {
		if (session != null) {
			session.setAttribute(Global.KEY_FRONTEND_USERNAME, user);
		}
	}

	/**
	 * 获取前台登录会员
	 * 
	 * @param request
	 * @return
	 */
	public static User getFrontUser(HttpServletRequest request, UserService userService) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return null;
		}
		User user = (User) session.getAttribute(Global.KEY_FRONTEND_USERNAME);
		if (user == null) {
			// 从Cookie中获取用户信息
			String cookieStr = getCookieByName(request, WebUtil.FRONT_USER_COOKIENAME);
			if (StringUtils.isNotEmpty(cookieStr)) {
				String userName = cookieStr.split(",")[0];
				// String pasword = cookieStr.split(",")[1];
				try {
					user = userService.getUserByLoginId(userName);
				} catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
				WebUtil.addFrontUser(session, user);
			}
		} else {
			try {
				User temp = user;
				user = userService.getUserByLoginId(user.getLoginId());

				user.setReason(temp.getReason());
				user.setGameid(temp.getGameid());
				user.setGametype(temp.getGametype());
				user.setChannel(temp.getChannel());
				user.setRoomid(temp.getRoomid());
				user.setTaskId(temp.getTaskId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return user;
	}

	public static String getContextPath(HttpServletRequest request) {
		return request.getContextPath();
	}

	public static Admin getAdmin(HttpServletRequest request) {
		if (request == null) {
			AdminService adminService = (AdminService) SpringUtil.getBean("adminService");
			try {
				return adminService.getAdminById(0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		HttpSession session = request.getSession();
		if (session == null) {
			return null;
		}
		if (session.getAttribute(Global.KEY_BACKEND_USER) == null) {
			return null;
		}
		Admin admin = (Admin) session.getAttribute(Global.KEY_BACKEND_USER);
		return admin;
	}
}
